﻿/*
* 作者:haojielyb
* 邮箱:haojielyb@qq.com
*/

using Furion.DependencyInjection;
using Furion.Logging.Extensions;
using Lxb.Model;
using OTHMqttClient.model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace FaceMqttClient

{
    public class OthUserService : ITransient
    {
        private readonly ISugarQueryable<Users> repository; // 仓储对象：封装简单的CRUD
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        private readonly string[] schools;
        private string path = AppDomain.CurrentDomain.BaseDirectory;

        public OthUserService(ISqlSugarClient db)
        {
          
            this.db = db.CopyNew();    // 推荐操作
            repository = this.db.Queryable<Users>();
         
            schools = new[] { "迁西县第二中学" };
        }

        public Users Get(int user_id)
        {
            try
            {
                var u = repository.Where(u => u.user_id == user_id).First();
                return u;
            }
            catch (Exception e)
            {

                throw e;
            }
            
           
        }

        public Tuple<bool, string> cantel(Users user, vcaller_group cg)
        {

            if (cg!=null && cg.cost > 0)
            {
                var wall = db.Queryable<wall>().Where(w => w.user_id == user.user_id).First();
                if (wall == null) {
                    return new Tuple<bool, string>(false, "余额不足");
                }
                if (wall.PV < cg.cost * 100 * (cg.call_long / 60))
                {
                    return new Tuple<bool, string>(false, "余额不足");
                }

            }
            else
            {

                if (user.kqtime > DateTime.Now.Date)
                {
                    return new Tuple<bool, string>(true, "");
                }
                else
                {
                    var st = schools.Contains(user.slname);

                    return new Tuple<bool, string>(st, "您不可以打电话");
                }

            }


            return new Tuple<bool, string>(true, "");
        }


        public List<VrfidUsers> Getall(String devid, int size = 50, int page = 0)
        {
            var dev_ = db.Queryable<Device>().Where(dev => dev.SN == devid && dev.down != 0).First();

            if (dev_ == null)
            {
                return null;
            }


            var school = dev_.school;

            var aschool = db.Queryable<School>().Where(sc => sc.name == school).First();

            if (aschool == null)
            {
                aschool = new School { zhusu = "", zoudu = "" };
            }
            var datestr = "2018/1/1";

            var datetime = Convert.ToDateTime(datestr);

            var afd = db.Queryable<Face_down_log>().Where(fd => fd.SN == devid).Max(fd => fd.time);

            if (afd > datetime)
            {
                datetime = afd;
            }

            var devdata = db.Queryable<Device_data>().Where(dd => dd.lxb_device == dev_.Id).ToList();

            var sql = $"  INSERT INTO lxb_face_down_log(uid,time,status,SN) " +
                $" select user_id as uid, uptime as time,  0 as status, '{devid}' as SN from lxb_user" +
                $" where  feature<>'' and  slname='{school}' and  uptime > '{datetime.ToString("yyyy/MM/dd HH:mm:ss")}'";

            foreach (var wdev in devdata)
            {
                if (wdev.state > 0)
                {
                    sql = sql + $" and  state =   {wdev.state}";
                }

                if (!String.IsNullOrEmpty(wdev.classname))
                {
                    sql = sql + $" and  clname = '{wdev.classname}'";
                }
            }

            db.Ado.ExecuteCommand(sql);

            var avu = db.Queryable<Face_down_log, Users>((fd, u) =>
       new JoinQueryInfos(
           JoinType.Inner, fd.uid == u.user_id)
       ).Where((fd, u) => fd.status == 0 && fd.times < 5 && u.feature != "" && fd.SN == devid)
       .Select((fd, u) => new VrfidUsers
       {
           Id = fd.Id,
           face = u.feature,
           Extinfo = u.clname,
           slname = u.slname,
           UserInfo = u.username,
           uname = u.user_id,
           zschool = u.zschool,
           dx = u.dx,
           rfid = u.rfid,
           state = u.state,
           uptime = fd.time
       })
       .OrderBy(fd => fd.Id, OrderByType.Asc).Take(size).ToList();


            //try
            //{
            //    item.face = db.Queryable<Face>().Where(f => f.uid == item.user_id).First().face;
            //}
            //catch
            //{
            //    item.face = null;
            //}
            //.Skip(page * size).Take(size)

            return avu;
        }

        private String dellasttime = "";

        public List<Users_del> GetDel(String devid, int size = 50, int page = 0)
        {
            var dev_ = db.Queryable<Device>().Where(dev => dev.SN == devid).First();

            if (dev_ == null)
            {
                return null;
            }

            var school = dev_.school;

            var datestr = "2018/1/1";

            var datetime = Convert.ToDateTime(datestr);
            try
            {
                datestr = System.IO.File.ReadAllText($"{path}dev/{devid}_d.cfg");
                datetime = Convert.ToDateTime(datestr);
            }
            catch (Exception)
            {
                datestr = "2018/1/1";
            }

            var lst = db.Queryable<Users_del>().Where(d => d.deltime > datetime && d.School == school).OrderBy(d => d.deltime, OrderByType.Asc).Skip(page * size).Take(size).ToList();
            if (lst.Count > 0)
            {
                dellasttime = lst.Last().deltime.ToString("yyyy/MM/dd HH:mm:ss");
            }
            if (lst.Count < size && (!String.IsNullOrEmpty(dellasttime)))
            {
                try
                {
                    if (!Directory.Exists($"{path}dev/"))
                    {
                        Directory.CreateDirectory($"{path}dev/");
                    }
                    System.IO.File.WriteAllText($"{path}dev/{devid}_d.cfg", dellasttime);

                }
                catch (Exception ex)
                {

                    ex.Message.LogInformation();
                }

            }
            return lst;
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="base64Img"></param>
        /// <param name="imgPath"></param>
        /// <param name="imgFormat">EX: System.Drawing.Imaging.Jpeg </param>
        public void SaveFile(VUsers u)
        {
            var imgPath = @$"E:\weixin\face_build\{u.user_id}.jpg";
            File.Exists(imgPath);
            var dateTime = File.GetLastWriteTime(imgPath);
            if (dateTime > u.uptime)
            {
                return;
            }
            string dir = Path.GetDirectoryName(imgPath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            OthTool.Base64StringToImage(u.face, imgPath);



        }
        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="SN"> 设备SN</param>
        /// <param name="id">id</param>
        /// <param name="status">状态</param>
        /// <param name="why">原因</param>
        /// <returns></returns>

        internal bool Upstate(String SN, String ids, int status = 1, string why = "")
        {


            var sql = "";
            if (status == 1)
            {
                sql = $"update  lxb_face_down_log  set status =1 where SN='{SN}' and  id in ({ids})";
            }
            else
            {
                sql = $"update  lxb_face_down_log  set status =0 ,why='{why}',times=times+1  where SN='{SN}' and  id in ( {ids})";
            }

            //    sql.LogWarning();

            db.Ado.ExecuteCommandAsync(sql);
            return true;

        }
    }
}